import React from "react";
import { View, Radio, Image, Text, Button } from "@tarojs/components";
import { useDispatch, useSelector } from "react-redux";
import {
  addToCarCountActionCreator,
  subToCarCountActionCreator,
  switchCarStateActionCreator,
  switchCarStateAllActionCreator,
} from "../../actions/car";

const Home = () => {
  const carList = useSelector((state) => state.car.carList);
  const totalPrice = carList
    .filter((v) => v.state)
    .reduce((p, n) => {
      return p + n.count * n.price;
    }, 0);
  const totalState = carList.every((v) => v.state);

  const dispatch = useDispatch();
  return (
    <View className="car">
      <View className="list">
        {carList.map((v, i) => {
          return (
            <View className="list-item" key={i}>
              <View className="radio">
                <Radio
                  checked={v.state}
                  onClick={() => dispatch(switchCarStateActionCreator(v))}
                ></Radio>
              </View>
              <View className="left">
                <Image src={v.image}></Image>
              </View>
              <View className="right">
                <Text>{v.title}</Text>
                <Text className="price">￥：{v.price}</Text>
                <View className="step">
                  <Button
                    size="mini"
                    onClick={() => {
                      if (process.env.TARO_ENV === "h5" && v.count === 1) {
                        return;
                      }
                      dispatch(subToCarCountActionCreator(v));
                    }}
                    disabled={v.count === 1}
                  >
                    -
                  </Button>
                  <Text>{v.count}</Text>
                  <Button
                    size="mini"
                    onClick={() => dispatch(addToCarCountActionCreator(v))}
                  >
                    +
                  </Button>
                </View>
              </View>
            </View>
          );
        })}
      </View>

      <View>
        <Radio
          checked={totalState}
          onClick={() => dispatch(switchCarStateAllActionCreator(!totalState))}
        ></Radio>
        <Text>￥：{totalPrice.toFixed(2)}元</Text>
      </View>
    </View>
  );
};

export default Home;
